package com.gm.wholesale.module.good.ui.goodManger;

import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseui.baseListviewUI.BaseGridFragment;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.network.HttpServicesHolder;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.wholesale.R;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.module.good.GoodType;
import com.gm.wholesale.module.good.api.IGoodApi;
import com.gm.wholesale.module.good.bean.GoodListBean;
import com.gm.wholesale.module.good.model.GoodModel;
import com.gm.wholesale.module.good.view.GoodFunctionView;
import com.gm.wholesale.module.good.view.GoodItemTagView;
import com.gm.wholesale.module.good.view.GoodKindTabView;
import com.gm.wholesale.module.kind.bean.KindBean;
import com.gm.wholesale.util.Utils;
import com.google.android.material.tabs.TabLayout;

import java.util.List;

import io.reactivex.Observable;

public class GoodListFragment extends BaseGridFragment<GoodListBean, BasePageData<GoodListBean>> {
    private TabLayout mTabLayout;
    private Long mCategoryId;
    private GoodFunctionView mCurrentFunctionView = null;


    @Override
    public void initPullToRefreshListView() {
        super.initPullToRefreshListView();
        setBodybg(getResources().getColor(R.color.page_bg));
        mGridView.setNumColumns(4);
        mGridView.setHorizontalSpacing(10);
        mGridView.setVerticalSpacing(10);
    }

    @Override
    protected void onCreateContentHeader(ViewGroup parent) {
        super.onCreateContentHeader(parent);
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_good_mange_list_header, parent);
        mTabLayout = view.findViewById(R.id.tabLayout);
        getKind();
    }

    @Override
    public void onRefreshView() {
        hidCurrentFunctionView();
        super.onRefreshView();

    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        //新增商品，刷新整个商品，先获取类型在获取商品
        if (event.getCode() == EventBusType.UPDATE_GOOD_LIST.getType()) {
            getKind();
        }//修改商品，只需要刷新当前界面
        else if (event.getCode() == EventBusType.UPDATE_ONE_KIND_GOOD.getType()){
            refreshData();
        }
    }
    @Override
    public void onTouchClick() {
        hidCurrentFunctionView();
    }

    private void getKind() {
        ////是否基于sku筛选，0表示展示全部分类，1表示展示仅有商品的分类
        GoodModel.getCategory(this, 1, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(BaseListResp<KindBean> resp) {
                if (resp == null) return;
                showKindUI(resp.getDatas());
            }
        });
    }

    private void showKindUI(List<KindBean> kindBeans) {
        mTabLayout.removeAllTabs();
        if (kindBeans != null) {
            KindBean kindBean = new KindBean(0, "全部");
            kindBeans.add(0, kindBean);
        }
        for (KindBean kindBean : kindBeans) {
            TabLayout.Tab tab = mTabLayout.newTab();
            GoodKindTabView goodKindTabView = new GoodKindTabView(getActivity());
            goodKindTabView.setText(kindBean.getName());
            goodKindTabView.setTag(kindBean);
            tab.setCustomView(goodKindTabView);
            if (kindBean.getId() == 0) {
                goodKindTabView.showCheck();
            }
            mTabLayout.addTab(tab);
        }

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                GoodKindTabView goodKindTabView = (GoodKindTabView) tab.getCustomView();
                goodKindTabView.showCheck();
                KindBean kindBean = (KindBean) goodKindTabView.getTag();
                mCategoryId = kindBean.getId();
                if (kindBean.getId() <= 0) {
                    mCategoryId = null;
                }
                hidCurrentFunctionView();
                refreshData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                GoodKindTabView goodKindTabView = (GoodKindTabView) tab.getCustomView();
                goodKindTabView.showUnCheck();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });



    }


    @Override
    protected BaseAdapter createTempBaseAdapter() {
        return new CommonAdapter<>(getActivity(), mDatas, R.layout.list_good_manger_item) {
            @Override
            public void convert(ViewHolder viewHolder, final GoodListBean data) {
                viewHolder.setText(R.id.goodNameTv, data.getName());
                showUnitName(data, viewHolder.getView(R.id.textTagView));
                GoodFunctionView funcTionView = viewHolder.getView(R.id.goodFunctionView);
                showTopTagView(data, viewHolder.getView(R.id.tagView));
                viewHolder.getConvertView().setOnLongClickListener(v -> {
                    hidCurrentFunctionView();
                    mCurrentFunctionView = funcTionView;
                    funcTionView.showView(data, (result, errorMsg) -> {
                        mCurrentFunctionView = null;

                        if (result != null) {
                            if (result.getHandleType() == 1) { //刪除操作
                                mDatas.remove(result);
                                notifyListDataSetChanged();
                            }
                            else {
                                EvenBusUtil.updateOneKindGoodList();
                            }
                        }
                        funcTionView.hidView();

                    });

                    return false;
                });
                viewHolder.getConvertView().setOnClickListener(v -> {
                    if (RepeatClickUtils.check()){
                        return;
                    }
                    if (mCurrentFunctionView != null) {
                        mCurrentFunctionView.hidView();
                        mCurrentFunctionView = null;
                        return;
                    }
                    EvenBusUtil.showCreateGoodUI(data);

                });
            }
        };
    }

    public void onGridScrollStateChanged() {
        hidCurrentFunctionView();
    }

    private void hidCurrentFunctionView() {
        if (mCurrentFunctionView != null) {
            mCurrentFunctionView.hidView();
            mCurrentFunctionView = null;
        }
    }


    private void showTopTagView(GoodListBean data, TextView tagView) {
        if (data.isOnShelf()) {
            tagView.setBackgroundResource(R.drawable.good_tag_gree_shap);
            tagView.setTextColor(getResources().getColor(R.color.color_09a955));
            tagView.setText("已上架");
        } else {
            tagView.setBackgroundResource(R.drawable.good_tag_red_shap);
            tagView.setTextColor(getResources().getColor(R.color.color_FE5000));
            tagView.setText("已下架");
        }
    }

    private void showUnitName(GoodListBean goodBean, GoodItemTagView goodItemTagView) {
        int goodType = goodBean.getType();
        //非库存商品,没得单位，默认显示斤
        if (goodType == GoodType.UN_INVENTORY_GOOD) {
            goodItemTagView.showGreenText("斤");
        } else {
            List<GoodListBean.UnitsBean> unitsBeans = goodBean.getUnits();
            if (unitsBeans != null && !unitsBeans.isEmpty()) {
                for (GoodListBean.UnitsBean unitsBean : unitsBeans) {
                    //仅库存商品生效，1库存单位，2辅助单位
                    if (unitsBean.getType() == 1) {
                        String unitName = unitsBean.getName();
                        if (Utils.isWeightUnit(unitName)) {
                            goodItemTagView.showGreenText(unitName);
                        } else {
                            goodItemTagView.showRedText(unitName);
                        }
                        break;
                    }
                }
            }
        }

    }

    @Override
    protected HttpServicesHolder<?, BasePageData<GoodListBean>> getHttpServicesHolder(long index) {
        return new HttpServicesHolder<IGoodApi, BasePageData<GoodListBean>>() {
            @Override
            public Observable<BasePageData<GoodListBean>> getHttpObservable(IGoodApi api) {
                ArrayMap<String, Object> queryData = new ArrayMap<>();
                queryData.put("page", index);
                queryData.put("pageSize", 20);
                if (mCategoryId != null) {
                    queryData.put("categoryId", mCategoryId);
                }
                return api.getGoodList(queryData);
            }
        };
    }
}
